using System;
using System.Collections.Generic;
using System.Linq;
using BepInEx;
using Assets;
using HarmonyLib;
using Hearthstone;
using Hearthstone.Progression;
using PegasusLettuce;
using PegasusShared;
using PegasusUtil;
using UnityEngine;
using System.Threading;

namespace Mercenary
{
    [BepInPlugin(PluginInfo.PLUGIN_GUID, PluginInfo.PLUGIN_NAME, PluginInfo.PLUGIN_VERSION)]
    public class Main : BaseUnityPlugin
    {
        private readonly Harmony _harmony = new Harmony("hs.patch");
        private static bool isRunning = false;
        private static float sleepTime;
        private static float idleTime;
        private static bool enableTimeGear = false;
        private static int noFightTime=2;
        private static int pveFightTime=4;
        private static int pvpFightTime=1;
        private static bool initialize=false;
        private static int phaseID;

        private void OnGUI()
        {
            UtilsGui.BuildGui(ref Main.isRunning);
        }

        private void Awake()
        {
            this._harmony.PatchAll(typeof(Main));
        }

        private void Start()
        {
            if (UtilsArgu.Instance.Exists("rule"))
            {
                var item = UiItemConst.GetUiItemList().Find(
                    u => u.m_id==int.Parse(UtilsArgu.Instance.Single("rule")));
                if(null!=item) UtilsGui.modeConf=item;
            }
            if (UtilsArgu.Instance.Exists("behavior"))
            {
                var item = UiItemConst.GetUiItemList().Find(
                    u => u.m_id==(10+int.Parse(UtilsArgu.Instance.Single("behavior"))));
                if(null!=item) UtilsGui.strategyConf=item;
                if(UtilsGui.modeConf.m_id == UiItemConst.模式_自动佣兵任务.m_id)
                    UtilsGui.strategyConf = UiItemConst.策略_PVE默认;
            }
            if (UtilsArgu.Instance.Exists("team"))
            {
                UtilsTeam.m_teamName = UtilsArgu.Instance.Single("team");
            }
            if (UtilsArgu.Instance.Exists("map"))
            {
                var item = MapConst.GetMapList().Find(
                    m => m.m_name.Equals(UtilsArgu.Instance.Single("map")));
                if(null!=item) UtilsMap.m_currMap=item;
            }
            if (UtilsArgu.Instance.Exists("interval"))
            {
                System.Random rand = new System.Random();
                UtilsGui.pveInterval = int.Parse(UtilsArgu.Instance.Single(
                    "interval")) * 60 + rand.Next(-180, 180);
                if (UtilsGui.pveInterval >= 27*60 || UtilsGui.pveInterval <= 10*60)
                {
                    UtilsGui.pveInterval = 22 * 60 + rand.Next(-60, 60);
                }
            }
            if (UtilsArgu.Instance.Exists("path"))
            {
                UtilsGui.path=UtilsArgu.Instance.Single("path");
            }
            if (UtilsArgu.Instance.Exists("hash"))
            {
                UtilsGui.hash=UtilsArgu.Instance.Single("hash");
            }
            if (UtilsArgu.Instance.Exists("needHang"))
            {
                UtilsGui.needToHang = true;
            }
            else UtilsGui.needToHang = false;
            if (UtilsArgu.Instance.Exists("autoconcede"))
            {
                UtilsGui.autoConcede = true;
            }
            else UtilsGui.autoConcede = false;
            if (UtilsArgu.Instance.Exists("autocraft"))
            {
                UtilsGui.autoCraftConf = true;
            }
            else UtilsGui.autoCraftConf = false;
            if (UtilsArgu.Instance.Exists("autoupdate"))
            {
                UtilsGui.autoUpdateSkillConf = true;
            }
            else UtilsGui.autoUpdateSkillConf = false;
            if (UtilsArgu.Instance.Exists("autostart"))
            {
                UtilsGui.bEnable = true;
                Main.isRunning = true;
            }
            else
            {
                UtilsGui.bEnable = false;
                Main.isRunning = false;
            }

            //齿轮
            if (UtilsArgu.Instance.Exists("timeGear"))
            {
                enableTimeGear = true;
                noFightTime = int.Parse(UtilsArgu.Instance["timeGear"][0]);
                pveFightTime = int.Parse(UtilsArgu.Instance["timeGear"][1]);
                pvpFightTime = int.Parse(UtilsArgu.Instance["timeGear"][2]);
                UtilsLog.Log($"开启齿轮，" +
                    $"noFightTime={noFightTime}," +
                    $"pveFightTime={pveFightTime}," +
                    $"pvpFightTime={pvpFightTime}");
                HsMod.ConfigValue.Get().TimeGearValue = noFightTime;
                HsMod.ConfigValue.Get().IsQuickModeEnableValue = true;
                HsMod.ConfigValue.Get().TimeGearEnable = true;
            }
            else
            {
                enableTimeGear = false;
                UtilsLog.Log($"关闭齿轮");
                HsMod.ConfigValue.Get().TimeGearValue = 0;
                HsMod.ConfigValue.Get().IsQuickModeEnableValue = false;
                HsMod.ConfigValue.Get().TimeGearEnable = false;
            }
            UtilsLog.Log("启动");
        }
        private void OnDestroy()
        {
            this._harmony.UnpatchSelf();
        }

        /*
        //隐藏通行证奖励
        [HarmonyPrefix]
        [HarmonyPatch(typeof(Hearthstone.Progression.RewardTrack), "UpdateStatus")]
        public static bool _PreUpdateStatus(int rewardTrackId, int level,
            Hearthstone.Progression.RewardTrack.RewardStatus status,
            bool forPaidTrack, List<RewardItemOutput> rewardItemOutput)
        {
            if (!Main.isRunning) return true;
            if (status == Hearthstone.Progression.RewardTrack.RewardStatus.GRANTED)
            {
                Hearthstone.Progression.RewardTrack currentRewardTrack =
                    RewardTrackManager.Get().GetCurrentRewardTrack(Global.RewardTrackType.GLOBAL);
                if (currentRewardTrack != null)
                {
                    currentRewardTrack.AckReward(rewardTrackId, level, forPaidTrack);
                }
                Hearthstone.Progression.RewardTrack currentRewardTrack2 =
                    RewardTrackManager.Get().GetCurrentRewardTrack(Global.RewardTrackType.BATTLEGROUNDS);
                if (currentRewardTrack2 != null)
                {
                    currentRewardTrack2.AckReward(rewardTrackId, level, forPaidTrack);
                }
                return false;
            }
            return true;
        }
        */

        //拦截来访者画面
        [HarmonyPrefix]
        [HarmonyPatch(typeof(LettuceMapDisplay), "OnVisitorSelectionResponseReceived")]
        public static bool _PreOnVisitorSelectionResponseReceived()
        {
            if (!Main.isRunning)  return true;
            Network.Get().GetMercenariesMapVisitorSelectionResponse();
            return false;
        }

        /*
        //拦截显示点击开始画面
        //拦截佣兵升级界面
        [HarmonyPrefix]
        [HarmonyPatch(typeof(SplashScreen), "GetRatingsScreenRegion")]
        [HarmonyPatch(typeof(QuestPopups), "ShowNextQuestNotification")]
        [HarmonyPatch(typeof(EnemyEmoteHandler), "IsSquelched")]
        [HarmonyPatch(typeof(EndGameScreen), "ShowMercenariesExperienceRewards")]
        public static bool _PreIntercept()
        {
            return !Main.isRunning;
        }
        */

        /*
        //禁止窗口失去焦点
        [HarmonyPrefix]
        [HarmonyPatch(typeof(HearthstoneApplication), "OnApplicationFocus")]
        public static bool _PreFocus(bool focus)
        {
            return !Main.isRunning;
        }
        */

        //游戏阶段
        [HarmonyPostfix]
        [HarmonyPatch(typeof(LettuceMissionEntity), "ShiftPlayZoneForGamePhase")]
        public static void _PostShiftPlayZoneForGamePhase(int phase)
        {
            //UtilsLog.Log("_PostShiftPlayZoneForGamePhase phase " + phase.ToString());
            Main.phaseID = phase;
        }

        /*
        //拦截重连
        [HarmonyPrefix]
        [HarmonyPatch(typeof(DialogManager), "ShowReconnectHelperDialog")]
        [HarmonyPatch(typeof(ReconnectHelperDialog), "Show")]
        [HarmonyPatch(typeof(Network), "OnFatalBnetError")]
        public static bool _PreError()
        {
            if (!Main.isRunning) return true;
            Application.Quit();
            return false;
        }
        */

        /*
        //拦截分辨率大小限制
        [HarmonyPrefix]
        [HarmonyPatch(typeof(GraphicsResolution), "IsAspectRatioWithinLimit")]
        public static bool _PreIsAspectRatioWithinLimit(ref bool __result,
            int width, int height, bool isWindowedMode)
        {
            if (!Main.isRunning) return true;
            __result = true;
            return false;
        }
        */

        /*
        //拦截错误提示
        [HarmonyPrefix]
        [HarmonyPatch(typeof(AlertPopup), "Show")]
        public static bool _PreAlertPopupShow()
        {
            return !Main.isRunning;
        }
        */

        //弹出访客
        [HarmonyPostfix]
        [HarmonyPatch(typeof(LettuceMapDisplay), "ShouldShowVisitorSelection")]
        public static void PostShouldShowVisitorSelection(
            PegasusLettuce.LettuceMap map,ref bool __result)
        {
            if (!Main.isRunning || map == null) return;
            __result = false;
            if (map.HasPendingVisitorSelection &&
                map.PendingVisitorSelection.VisitorOptions.Count > 0)
            {
                Network.Get().MakeMercenariesMapVisitorSelection(0);
            }
        }

        //弹出揭示卡
        [HarmonyPrefix]
        [HarmonyPatch(typeof(LettuceMapDisplay), "DisplayNewlyGrantedAnomalyCards")]
        public static bool _PreDisplayNewlyGrantedAnomalyCards(
            global::LettuceMap lettuceMap, int completedNodeId)
        {
            return !Main.isRunning;
        }

        //游戏结束画面
        [HarmonyPostfix]
        [HarmonyPatch(typeof(GameEntity), "ShowEndGameScreen")]
        public static void PatchEndGameScreenShow(ref TAG_PLAYSTATE playState)
        {
            try
            {
                switch (playState)
                {
                    case TAG_PLAYSTATE.WINNING:
                    case TAG_PLAYSTATE.WON:
                        ++UtilsInfo.PvpWin;
                        break;
                    case TAG_PLAYSTATE.CONCEDED:
                    case TAG_PLAYSTATE.LOST:
                    case TAG_PLAYSTATE.LOSING:
                        ++UtilsInfo.PvpLose;
                        break;
                    case TAG_PLAYSTATE.TIED:
                        break;
                    default:
                        break;
                }
            }
            catch {}
        }

        //地图相关
        [HarmonyPostfix]
        [HarmonyPatch(typeof(global::LettuceMap), "CreateMapFromProto")]
        public static void _PostCreateMapFromProto(PegasusLettuce.LettuceMap lettuceMap)
        {
            UtilsLog.Log("[地图信息识别]");
            if (!Main.isRunning || lettuceMap == null) return;

            NetCache.NetCacheMercenariesVillageVisitorInfo netObject =
                NetCache.Get().GetNetObject<NetCache.NetCacheMercenariesVillageVisitorInfo>();
            if (netObject != null)
            {
                foreach (MercenariesVisitorState mercenariesVisitorState in netObject.VisitorStates)
                {
                    if (mercenariesVisitorState.ActiveTaskState.Status_ ==
                        MercenariesTaskState.Status.COMPLETE)
                    {
                        UtilsLog.Log(string.Format("[地图信息识别] [任务Id={0}]完成",
                            mercenariesVisitorState.ActiveTaskState.TaskId));
                        Network.Get().ClaimMercenaryTask(
                            mercenariesVisitorState.ActiveTaskState.TaskId);
                    }
                }
            }
            foreach (LettuceMapNode lettuceMapNode in lettuceMap.Nodes)
            {
                if (GameUtils.IsFinalBossNodeType((int)lettuceMapNode.NodeTypeId) &&
                    lettuceMapNode.NodeState_ == LettuceMapNode.NodeState.COMPLETE)
                {
                    UtilsLog.Log(string.Format("[地图信息识别] 回到悬赏面板"));
                    SceneMgr.Get().SetNextMode(SceneMgr.Mode.LETTUCE_BOUNTY_BOARD,
                        SceneMgr.TransitionHandlerType.NEXT_SCENE, null, null);
                    return;
                }
            }
            if (lettuceMap.HasPendingTreasureSelection &&
                lettuceMap.PendingTreasureSelection.TreasureOptions.Count > 0)
            {
                string[] findTreasure =
                {
					//T0
					"刺杀","强化飞刺","冷酷严冬","自然之噬","雷暴之怒","强化闪电箭",
                    "元素研究","火焰之杖","月之祝福","火炮轰击","宝箱","灵魂虹吸","吸取灵魂",
					//T1
					"火球齐射","蔓延炸弹","便携冰墙","冰霜之杖","冰霜齐射",
                    "自然之杖",
					//T2
					"火舌图腾","元素之力","精灵旗帜","冰霜之环",
                    "部落的旗帜","联盟战争旗帜","暴风城战袍","血之契印","奥格瑞玛战袍",
                    "隐蔽武器","近在眼前",
					//T3
					"药膏瓶","强韧","萨隆邪铁护甲","防护之戒","火炮弹幕","乔丹法杖"
                };
                List<string> treasureList = new List<string>();
                foreach (int dbId in lettuceMap.PendingTreasureSelection.TreasureOptions)
                {
                    string cardId = GameUtils.TranslateDbIdToCardId(dbId, false);
                    string name = DefLoader.Get()?.GetEntityDef(cardId)?.GetName();
                    UtilsLog.Log($"[宝藏测试] {name}");
                    if (name.Length > 0 &&
                        Char.IsNumber(name[name.Length - 1]))
                        name = name.Substring(0, name.Length - 1);
                    treasureList.Add(name);
                }
                int findIndex = -1;
                foreach (var iter in findTreasure)
                {
                    findIndex = treasureList.IndexOf(iter);
                    if (findIndex != -1)
                        break;
                }
                UtilsLog.Log($"[地图信息识别] 选择第{findIndex + 1}个宝藏");
				Network.Get().MakeMercenariesMapTreasureSelection(Math.Max(0, findIndex));
            }
            if (lettuceMap.HasPendingVisitorSelection &&
                lettuceMap.PendingVisitorSelection.VisitorOptions.Count > 0)
            {
                UtilsLog.Log(string.Format("[地图信息识别] 选择第一个来访者"));
                Network.Get().MakeMercenariesMapVisitorSelection(0);
            }
        }

        //节点选择
        [HarmonyPostfix]
        [HarmonyPatch(typeof(LettuceMapDisplay), "TryAutoNextSelectCoin")]
        public static void _PostTryAutoNextSelectCoin(LettuceMapDisplay __instance)
        {
            if (!Main.isRunning)  return;
            UtilsLog.Log("[节点选择]");
            LettuceMap map = (global::LettuceMap)Traverse.Create(
                __instance).Field("m_lettuceMap").GetValue();
            Main.ResetIdle();
            UtilsNode.SelectNextNode(map);
        }
    
        [HarmonyPostfix]
        [HarmonyPatch(typeof(LettuceMapDisplay), "OnLettuceMapChooseNodeResponseReceived")]
        public static void _PostOnLettuceMapChooseNodeResponseReceived()
        {
            LettuceMapChooseNodeResponse lettuceMapChooseNodeResponse =
                Network.Get().GetLettuceMapChooseNodeResponse();
            if (lettuceMapChooseNodeResponse == null ||
                !lettuceMapChooseNodeResponse.Success)
            {
                UtilsLog.Log(string.Format("[节点选择] 应答失败，返回村庄重试"));
                Main.Sleep(10);
                UtilsCom.GotoSceneVillage();
                return;
            }
        }

        /*
        [HarmonyPrefix]
        [HarmonyPatch(typeof(MercenariesSeasonRewardsDialog), "ShowWhenReady")]
        public static bool _PreShowWhenReady(MercenariesSeasonRewardsDialog __instance)
        {
            if (!Main.isRunning) return true;

            UtilsLog.Log("显示天梯奖励");
            MercenariesSeasonRewardsDialog.Info info =
                (MercenariesSeasonRewardsDialog.Info)Traverse.Create(
                    __instance).Field("m_info").GetValue();
            Network.Get().AckNotice(info.m_noticeId);
            return false;
        }
        */

        /*
        [HarmonyPrefix]
        [HarmonyPatch(typeof(RewardPopups), "ShowMercenariesRewards")]
        public static bool _PreShowMercenariesRewards(ref bool autoOpenChest,
            ref NetCache.ProfileNoticeMercenariesRewards rewardNotice, Action doneCallback = null)
        {
            if (!Main.isRunning) return true;

            UtilsLog.Log("显示奖励");
            Main.Sleep(10);

            autoOpenChest = true;
            if (rewardNotice.RewardType !=
                ProfileNoticeMercenariesRewards.RewardType.REWARD_TYPE_PVE_CONSOLATION)  return true;

            Network.Get().AckNotice(rewardNotice.NoticeID);
            if (doneCallback != null) doneCallback();

            return false;
        }
        */

        /*
        [HarmonyPostfix]
        [HarmonyPatch(typeof(RewardBoxesDisplay), "RewardPackageOnComplete")]
        public static void _PostRewardPackageOnComplete(RewardBoxesDisplay.RewardBoxData boxData)
        {
            if (!Main.isRunning) return;
            UtilsLog.Log("点击奖励");
            boxData.m_RewardPackage.TriggerPress();
        }
        */

        /*
        [HarmonyPostfix]
        [HarmonyPatch(typeof(RewardBoxesDisplay), "OnDoneButtonShown")]
        public static void _PostOnDoneButtonShown(Spell spell, object userData)
        {
            if (!Main.isRunning) return;
            UtilsLog.Log("点击完成按钮");
            RewardBoxesDisplay.Get().m_DoneButton.TriggerPress();
            RewardBoxesDisplay.Get().m_DoneButton.TriggerRelease();
        }
        */

        private void GameInit()
        {
            if (InactivePlayerKicker.Get() != null)
            {
                Main.initialize = true;
                InactivePlayerKicker.Get().SetKickSec(180000f);
                Main.Sleep(8);
            }
        }

        public static void Sleep(int time)
        {
            Main.sleepTime += (float)time;
        }

        private static void ResetIdle()
        {
            UtilsLog.Log("[空闲时间] 重置空闲时间");
            Main.idleTime = 0f;
        }

        private void CheckIdleTime()
        {
            Main.idleTime += Time.deltaTime;
            if (UtilsGui.modeConf.m_id != UiItemConst.模式_真人PVP.m_id && Main.idleTime > 1200f)
            {
                if (Main.idleTime > 1260f && UtilsGui.pvpDelayTime < 120)
                {
                    Application.Quit();
                }
                if (GameState.Get() != null && UtilsGui.pvpDelayTime < 120)
                {
                    UtilsLog.Log("[IDLE]1200s 投降");
                    GameState.Get().Concede();
                }
            }
            if (Main.idleTime > 1200f)
            {
                if (Main.idleTime > 1260f && UtilsGui.pvpDelayTime < 20)
                {
                    UtilsLog.Log("[IDLE] 1260s 游戏关闭");
                    Application.Quit();
                }
                if (GameState.Get() != null && UtilsGui.pvpDelayTime < 20)
                {
                    UtilsLog.Log("[IDLE] 1200s 投降");
                    GameState.Get().Concede();
                    UtilsCom.GotoSceneVillage();
                    UtilsLog.Log("可能是卡死了，返回村庄看看");
                    Main.Sleep(5);
                }
            }
        }

        private void Update()
        {
            if (!Main.isRunning) return;
            CheckIdleTime();
            if ((double)(Time.realtimeSinceStartup - Main.sleepTime) <= 0.01) return;
            Main.sleepTime = Time.realtimeSinceStartup;
            if (!Main.initialize)
            {
                GameInit();
                return;
            }

            GameMgr gameMgr = GameMgr.Get();
            GameType gameType = gameMgr.GetGameType();
            SceneMgr sceneMgr = SceneMgr.Get();
            SceneMgr.Mode mode = sceneMgr.GetMode();
            GameState gameState = GameState.Get();

            //查找比赛
            if (gameMgr.IsFindingGame())
            {
                UtilsLog.LogStra("[状态] 查找比赛，休息3秒");
                Main.Sleep(3);
                return;
            }

            //天梯卡组界面时直接回到佣兵模式
            if (mode == SceneMgr.Mode.TOURNAMENT)
            {
                UtilsLog.Log("[天梯卡组界面] 直接回到佣兵模式");
                UtilsCom.GotoSceneVillage();
                Main.Sleep(5);
                Main.ResetIdle();
                return;
            }

            //PVP角斗场
            if (gameType == GameType.GT_UNKNOWN &&
                mode == SceneMgr.Mode.LETTUCE_PLAY && gameState == null)
            {
                if (UtilsGui.modeConf.m_id != UiItemConst.模式_真人PVP.m_id)
                {
                    UtilsLog.Log("[状态] 目前处于角斗场，切换到村庄，休息5秒");
                    UtilsCom.GotoSceneVillage();
                    Main.Sleep(5);
                    Main.ResetIdle();
                    return;
                }

                //制作佣兵和升级技能
                //UtilsMerc.CraftNewMerc();
                //UtilsMerc.UpgradeSkillAndEquip();

                //后续PVP策略多了之后，根据环境或者上局对战重新选择策略
                //然后根据策略自动组队，切换队伍，重新开打
                //UtilsGui.strategyConf=“新策略”，根据环境自动推荐最佳策略
                UtilsTeam.UpdateTeam();

                UtilsLog.Log("[状态] PVP开始寻找对手...");
                if (UtilsTeam.m_teamId != -1)
                {
                    GameMgr.Get().FindGame(GameType.GT_MERCENARIES_PVP,
                        FormatType.FT_WILD, 3743, 0, 0L, null, null, false,
                        null, null, UtilsTeam.m_teamId, GameType.GT_UNKNOWN);
                }
                else 
                {
                    UtilsLog.Log("[队伍选择] 当前无队伍可选，请检查");
                    UtilsGui.errCode = "佣兵队伍设置错误";
                    Main.isRunning = false;
                }
                return;
            }

            //村子
            if (gameType == GameType.GT_UNKNOWN && gameState == null &&
                mode == SceneMgr.Mode.LETTUCE_VILLAGE)
            {
                if (UtilsGui.modeConf.m_id == UiItemConst.模式_真人PVP.m_id)
                {
                    //跳转到PVP
                    UtilsLog.Log("[状态] 目前处于村庄，切换到PVP，休息5秒");
                    UtilsCom.GotoScenePlay();
                }
                else
                {
                    //跳转到PVE
                    UtilsLog.Log("[状态] 目前处于村庄，切换到PVE，休息5秒");
                    UtilsCom.GotoSceneMap();
                }
                Main.Sleep(5);
                Main.ResetIdle();
                return;
            }

            //主界面
            if (gameType == GameType.GT_UNKNOWN &&
                mode == SceneMgr.Mode.HUB && gameState == null)
            {
                UtilsLog.Log("[状态] 目前处于主界面，切换到村庄，休息5秒");
                UtilsCom.GotoSceneVillage();
                Main.Sleep(5);
                return;
            }

            //悬赏面板
            if (gameType == GameType.GT_UNKNOWN && gameState == null &&
                mode == SceneMgr.Mode.LETTUCE_BOUNTY_BOARD)
            {
                if (UtilsGui.modeConf.m_id == UiItemConst.模式_真人PVP.m_id)
                {
                    UtilsLog.Log("[状态] 目前处于悬赏面板，切换到村庄，休息5秒");
                    UtilsCom.GotoSceneVillage();
                    Main.Sleep(5);
                    Main.ResetIdle();
                    return;
                }
                UtilsLog.Log("[状态] 目前处于悬赏面板，选择地图，休息5秒");
                UtilsMap.SelectMap();
                Main.Sleep(5);
                Main.ResetIdle();
                return;
            }

            //队伍选择
            if (gameType == GameType.GT_UNKNOWN && gameState == null &&
                mode == SceneMgr.Mode.LETTUCE_BOUNTY_TEAM_SELECT)
            {
                if ((double)Main.idleTime > 20.0)
                {
                    UtilsLog.Log("[状态] 目前处于队伍选择，空闲时间超过20s，返回村庄");
                    UtilsCom.GotoSceneVillage();
                    Main.Sleep(5);
                    return;
                }
                UtilsMerc.CraftNewMerc();
                UtilsMerc.UpgradeSkillAndEquip();
                UtilsTeam.UpdateTeam();
                Main.Sleep(5);
                if (UtilsTeam.m_teamId != -1)
                {
                    UtilsTeam.SelectTeam();
                }
                else
                {
                    UtilsLog.Log("[队伍选择] 当前无队伍可选，请检查");
                    UtilsGui.errCode = "佣兵队伍设置错误";
                    Main.isRunning = false;
                }
                return;
            }

            //地图
            if (gameType == GameType.GT_UNKNOWN &&
                mode == SceneMgr.Mode.LETTUCE_MAP && gameState == null)
            {
                if ((double)Main.idleTime > 20.0)
                {
                    UtilsLog.Log("[状态] 目前处于地图，空闲时间超过20s，返回村庄");
                    UtilsCom.GotoSceneVillage();
                    Main.Sleep(5);
                    return;
                }
            }

            //游戏结束
            if (gameState == null || gameState.IsGameOver())
            {
                if (EndGameScreen.Get())
                {
                    PegUIElement hitbox = EndGameScreen.Get().m_hitbox;
                    Blizzard.T5.Core.Map<UIEventType, List<UIEvent.Handler>> eventListeners =
                        (Blizzard.T5.Core.Map<UIEventType, List<UIEvent.Handler>>)Traverse.Create(
                        hitbox).Field("m_eventListeners").GetValue();
                    if (hitbox != null)
                    {
                        hitbox.TriggerPress();
                        hitbox.TriggerRelease();
                        UtilsLog.Log("[对局结束] 悬赏结束，点击");
                        if (enableTimeGear) HsMod.ConfigValue.Get().TimeGearValue = noFightTime;
                        if (UtilsGui.modeConf.m_id == UiItemConst.模式_真人PVP.m_id)
                        {
                            //pvp结束
                            UtilsInfo.MercTeamCount();
                            UtilsGui.pvpRating = UtilsInfo.GetPVPrating();
                        }
                        Main.Sleep(4);
                        Main.ResetIdle();
                    }
                }
                return;
            }

            //天梯模式直接投降
            if (gameType == GameType.GT_RANKED &&
                mode == SceneMgr.Mode.GAMEPLAY &&
                gameState.IsGameCreatedOrCreating())
            {
                UtilsLog.Log("[对局结束] 传统模式投降");
                GameState.Get().Concede();
                Main.Sleep(5);
                Main.ResetIdle();
                return;
            }

            //排队中
            if (gameState != null &&
                ((gameType != GameType.GT_MERCENARIES_PVE &&
                gameType != GameType.GT_MERCENARIES_PVP) || sceneMgr.GetMode() !=
                SceneMgr.Mode.GAMEPLAY || !gameState.IsGameCreatedOrCreating()))
            {
                UtilsLog.Log("[状态] 排队中");
                Main.Sleep(5);
                return;
            }

            Main.Sleep(1);

            //开始对战
            if (0 != UtilsBattle.HandleBattle(phaseID, enableTimeGear,
                pveFightTime, pvpFightTime)) Main.ResetIdle();
        }
    }
}
